'use strict';
const db = uniCloud.database()
const dbHelper = require('db-helper')
const {uniIDConfigMerchant} = require('config')
const uniID = require('uni-id')
const {CLOUDURL} = require('config')
exports.main = async (event, context) => {
	//event为客户端上传的参数
	let {
		body
	} = event
	body = JSON.parse(body)
	if (!body) {
		return {
			code: 500,
			msg: '参数不正确'
		}
	}
	let {
		_id,
		detail,
		token,
		append
	// } = JSON.parse(body);
	} = body;

	if (!_id || !detail) {
		return {
			code: 500,
			msg: '参数不正确',
			param: body
		}
	}
	context.APPID = '__UNI__B9807A9'
	context.PLATFORM = 'h5'
	context.LOCALE = 'zh-Hans'
	const uniIDIns = uniID.createInstance({
		context: context,
		config: uniIDConfigMerchant
	})
	try {
		let payload = await uniIDIns.checkToken(token)
		if (payload.code) {
			return {
				code: 401,
				msg: "token无效，请重新登陆"
			}
		}
		let goods = await dbHelper.getById("t3ds-mall-goods", _id);
		if (!goods) {
			return {
				code: 500,
				msg: "商品不存在"
			}
		}
		// detail = detail.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function(match, capture) {
		// 	return match.replace(/src=[\'\"]?([^\'\"]*)[\'\"]?/i, function(match2, capture2) {
		// 		if (capture2.startsWith(CLOUDURL)) {
		// 			return `src="${capture2}"`
		// 		}
		// 		return `src="${CLOUDURL}/imageLoader/?url=${encodeURIComponent(capture2)}"`
		// 	})
		// })
		// detail = detail.replace(/url\(.+?\)/gi, function(match, capture) {
		// 	return match.replace(/(http(s?):\/\/)?([A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"\'])*)/gi, function(match2, capture2) {
		// 			if (match2.startsWith(CLOUDURL)) {
		// 				return match2
		// 			}
		// 			return `${CLOUDURL}/imageLoader/?url=${encodeURIComponent(match2)}`
		// 		})
		// })
		// goods.detail = goods.detail.replace(/<img/g, "<img referrerpolicy='no-referrer'")
		// goods.detail = goods.detail.replace(/<img/gi, function(match, capture) {
		// 	return "<img referrerpolicy='no-referrer'"
		// })
		if (append) {
			detail = goods.detail + detail;
		}
		
		await db.collection("t3ds-mall-goods").doc(_id).update({
			detail: detail
		})
		return {
			code: 200,
			data: detail
		}
	} catch (e) {
		console.error("更新商品详情遇到错误", e);
		return {
			code: 500,
			msg: e.message
		}
	}
}
